<template>
  <!--使用draggable组件-->
  <a-spin :spinning="spinning">
    <div class="core">
      <a-button style="margin-bottom: 10px" type="primary" @click="addNode" icon="plus"> 添加分组 </a-button>

      <!-- 左侧盒子 -->
      <div class="core_top">
        <draggable
          v-model="nodeList"
          @end="entLeft"
          :options="{ group: { name: 'itxst', pull: 'clone' }, sort: true }"
          animation="300"
          :move="onMoveLeft"
          filter=".core_top_content_node_active"
        >
          <transition-group class="core_top_transition">
            <div class="core_top_content" v-for="(item, index) in nodeList" :key="item.id">
              <!-- :class="item.status ? 'core_top_content_node core_top_content_node_active' : 'core_top_content_node'" -->
              <div
                :style="item.id in colorMap ? `background: ${colorMap[item.id]};` : ''"
                class="core_top_content_node"
              >
                {{ item.name }} <span v-if="item.documentation">({{item.documentation}})</span>
              </div>
              <div v-if="index < nodeList.length - 1" class="core_top_content_icon">
                <a-icon type="arrow-right" />
              </div>
            </div>
          </transition-group>
        </draggable>
      </div>

      <!-- 右侧盒子 -->
      <div class="core_bottom">
        <DraggableList
          v-if="!spinning"
          ref="DraggableRef"
          @f_delGroup="s_delGroup"
          @f_delnode="s_delnode"
          @f_addColor="addColor"
          :f_groupList="groupList"
          :nodeOrderList="nodeOrderList"
        />
      </div>
    </div>
  </a-spin>
</template>
<script>
import { findAllByFormid } from '@/api/workflow/act_dsn_form_scat.js'
export default {
  props: {
    modelKey: {
      type: String,
      require: true,
    },
    formid: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      colorMap: {}, // 记录各个环节组的颜色值
      spinning: true, // 加载动画
      groupList: [
        // {
        //   name: '分组一',
        //   daytype: 92000,
        //   limitable: 3200,
        //   daylimit: 15,
        //   daywarn: -5,
        //   list: [{ id: 1, name: '占位符' }],
        // },
      ], // 分组
      //定义要被拖拽对象的数组
      nodeList: [], // 流程节点列表
      nodeOrderList: [], // 环节的顺序
    }
  },
  created() {
    // 获取流程环节节点 和 环节组配置
    this.findAllByFormid()
  },
  methods: {
    // 获取组装数据
    f_checkNode() {
      return this.$refs.DraggableRef.f_checkNode()
    },
    // 重置环节组
    f_reset() {
      // 重置可配置状态
      for (let i = this.nodeList.length - 1; i >= 0; i--) {
        this.nodeList[i].status = false
      }
      // 重置颜色
      this.colorMap = {}
      console.log(' this.nodeList',  this.nodeList)
      this.$refs.DraggableRef.f_reset()
    },
    // 删除环节组
    s_delGroup(steplist) {
      // 1. 删除分组下的节点需要重新改为可配置
      const activeArr = []
      steplist.forEach((v) => {
        activeArr.push(v.id)
      })
      this.nodeList.forEach((v) => {
        if (activeArr.includes(v.id)) {
          this.delColor(v.id)
          v.status = false
        }
      })
    },
    // 新增分组
    addNode() {
      // console.log('新增分组')
      this.$refs.DraggableRef.f_addNode()
    },
    // 清除背景颜色
    delColor(id) {
      delete this.colorMap[id]
      this.$set(this.colorMap, id, '#ccc')
      // this.colorMap[id] = 'red'
      // console.log('删除', this.colorMap)
    },
    // 添加背景颜色
    addColor(color, list) {
      // console.log('添加颜色', color, list)
      list.forEach((v) => {
        if (v.id != 1) {
          this.$set(this.colorMap, v.id, color)
        }
      })
    },
    // 子节点删除配置节点
    s_delnode(node) {
      console.log('node', node)
      // 把删除的节点重新设置为可拖动配置
      for (let v of this.nodeList) {
        if (v.id == node.id) {
          this.delColor(node.id)
          v.status = false
          break
        }
      }
    },
    //左边往右边拖动时的事件
    entLeft(e) {
      // console.log('拖动完成(父)', e)
    },
    //move回调方法 控制是否可拖拽
    onMoveLeft(e, originalEvent) {
      // 拖动到的数组 e.relatedContext.list
      // 原数组的位置 e.draggedContext.index
      // 拖动到数组的位置 e.draggedContext.futureIndex
      // 当前要新增的元素 e.draggedContext.element
      // console.log('拖动下标', e.draggedContext.index, e.draggedContext.futureIndex)

      // 目标数组
      let targetArr = JSON.parse(JSON.stringify(e.relatedContext.list))
      const addid = e.draggedContext.element.id
      // 判断是否存在同名的节点
      for (let v of targetArr) {
        if (v.id == addid) {
          return false
        }
      }
      // 补上当前新增的环节
      targetArr.push(e.draggedContext.element)
      // 校验拖动到的分组是否是连续的
      let check = this.checkContinuity(targetArr)
      // 修改节点status为已配置
      if (check) {
        for (let v of this.nodeList) {
          if (v.id == e.draggedContext.element.id) {
            v.status = true
            break
          }
        }
        // 给新增节点添加背景颜色
        for (let v of targetArr) {
          // console.log('v', v, v.bgcolor)
          if (v.bgcolor) {
            this.$set(this.colorMap, e.draggedContext.element.id, v.bgcolor)
            e.draggedContext.element.bgcolor = v.bgcolor
            break
          }
        }
      }

      // console.log('加', targetArr)
      // console.log('是否拖动', check)
      return check
    },
    // 校验拖动节点是否连续
    checkContinuity(targetArr) {
      // console.log('targetArr', targetArr)
      let stepArr = []
      targetArr.forEach((v) => {
        if (v.id != 1) {
          stepArr.push(v.id)
        }
      })
      if (stepArr.length == 0) {
        return true
      }
      // 找到匹配的开始节点
      let startIndex = null
      for (let i = 0; i <= this.nodeOrderList.length - 1; i++) {
        if (stepArr.includes(this.nodeOrderList[i])) {
          startIndex = i
          break
        }
      }
      console.log('stepArr', stepArr)
      // console.log('开始', startIndex, '结束', (startIndex + stepArr.length - 1))
      // 判断是否是连续的
      for (let i = startIndex; i <= startIndex + stepArr.length - 1; i++) {
        if (stepArr.includes(this.nodeOrderList[i]) == false) {
          // 一旦主连续环节有一段和当前环节不匹配, 说明有节点不连续
          return false
        }
      }
      return true
    },
    // 获取流程环节节点 和 环节组配置
    findAllByFormid() {
      this.spinning = true
      findAllByFormid(this.formid, this.modelKey)
        .then((res) => {
          console.log('办结时限组配置', res)
          if (res.code == 0) {
            // 流程环节配置
            let nodelist = res.data?.nodelist || []
            // 环节组配置
            let configlist = res.data?.configlist || []
            nodelist.forEach((v) => {
              this.nodeOrderList.push(v.id)
              this.nodeList.push({ id: v.id, name: v.name, status: false, documentation: v.documentation })
            })

            // 初始化占位符 和 初始化环节可编辑状态
            let activeArr = [] // 初始化激活的节点
            configlist.forEach((v) => {
              // 初始化的时候没有背景颜色给一个背景颜色
              if (!v.bgcolor) {
                v.bgcolor = this.setRgbColor()
              }

              if (v.list.length == 0) {
                v.list.push({ id: 1, name: '占位符' })
              } else {
                v.list.forEach((s) => {
                  s.bgcolor = v.bgcolor
                  this.colorMap[s.stepid] = v.bgcolor
                  s.id = s.stepid
                  activeArr.push(s.stepid)
                })
              }
            })
            // 激活已经编辑的节点
            this.nodeList.forEach((v) => {
              if (activeArr.includes(v.id)) {
                v.status = true
              }
            })
            this.groupList = configlist
            // console.log('回显groupList', this.groupList)
            // console.log('回显nodeList', this.nodeList)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 获取随机背景色
    setRgbColor() {
      var r = parseInt(Math.random() * 200)
      var g = parseInt(Math.random() * 200)
      var b = parseInt(Math.random() * 200)

      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },
  },
  components: {
    draggable: () => import('vuedraggable'),
    DraggableList: () => import('@/views/base/DraggableList.vue'),
  },
}
</script>
<style lang="less" scoped>
.flex {
  display: flex !important;
  flex-direction: row !important;
}
.core {
  // border: 1px solid red;
  height: 80vh;

  &_top {
    // border: 1px solid blue;
    overflow: auto;
    &:extend(.flex);

    &_transition {
      border: 1px solid #eee;
      display: flex !important;
    }
    &_content {
      width: 150px;
      // border: 1px solid #000;
      &:extend(.flex);
      justify-content: space-between;

      &_icon {
        width: 35px;
        // border: 1px solid red;
        float: right;
        &:extend(.flex);
        align-items: center;
      }
      &_node {
        width: 100px;
        height: 100px;
        border: none;
        border-radius: 50%;
        &:extend(.flex);
        justify-content: center;
        align-items: center;
        background-color: #ccc;
        &_active {
          background-color: rgb(121, 231, 93);
        }
      }
    }
  }

  &_bottom {
    margin-top: 20px;
    height: 20%;
    // border: 1px solid pink;
  }
}
</style>